
/**
** \file       for.c
**
** \brief      this function parse the for rule
**
** \author     Ben M'rad Hanna, Laterem Hamza, Boillot Ulysse,
** De Olivera Guillaume, and Nguyen Viet Dung
**
** \version    0.8
**
** \date       26 Novembre 2010
**
*/

#include "rules.h"

static s_rulefor		*rule_for1(s_rulefor     *rfor)
{
  if (g_data->lexer != NULL && strcmp(g_data->lexer->token->id, "for") == 0)
    {
      g_data->lexer = g_data->lexer->next;

      if (g_data->lexer == NULL || g_data->lexer->token->type != TOKEN_WORD)
	return (NULL);

      rfor->in_for = calloc(1, strlen(g_data->lexer->token->id) + 1);
      rfor->in_for = strcpy(rfor->in_for, g_data->lexer->token->id);

      g_data->lexer = g_data->lexer->next;

      while (g_data->lexer != NULL &&
	     strcmp(g_data->lexer->token->id, "\n") == 0)
	g_data->lexer = g_data->lexer->next;

      return (rfor);
    }

  return (NULL);
}

static s_rulefor		*rule_for2(s_rulefor     *rfor)
{
  s_word			*tmp_word = NULL;
  int				size;

  size = strlen(g_data->lexer->token->id);
  if (strcmp(g_data->lexer->token->id, "in") == 0)
  {
    g_data->lexer = g_data->lexer->next;
    rfor->in_in = calloc(1, sizeof (s_word));

    tmp_word = rfor->in_in;

    while (g_data->lexer != NULL && g_data->lexer->token->type == TOKEN_WORD)
    {
      tmp_word->word = calloc(1, sizeof (char) * size + 1);
      tmp_word->word = strcpy(tmp_word->word, g_data->lexer->token->id);
      tmp_word->next = calloc(1, sizeof (s_word));
      tmp_word = tmp_word->next;

      g_data->lexer = g_data->lexer->next;
    }

    if (g_data->lexer == NULL)
    {
      free_word(rfor->in_in);
      rfor->in_in = NULL;

      return (NULL);
    }

    return (rfor);
  }

  return (NULL);
}

static s_rulefor		*rule_for3(s_rulefor     *rfor)
{
  if (strcmp(g_data->lexer->token->id, ";") == 0 ||
      strcmp(g_data->lexer->token->id, "\n") == 0)
  {
    g_data->lexer = g_data->lexer->next;

    while (g_data->lexer != NULL && strcmp(g_data->lexer->token->id, "\n") == 0)
      g_data->lexer = g_data->lexer->next;

    return (rfor);
  }

  free_word(rfor->in_in);
  rfor->in_in = NULL;

  return (NULL);
}

s_rulefor                       *rule_for(s_rulefor     *rfor)
{
  if (rfor == NULL)
    return (NULL);

  if (rule_for1(rfor) != NULL)
  {
    if (rule_for2(rfor) == NULL)
      return (NULL);

    if (rule_for3(rfor) == NULL)
      return (NULL);

    return (rfor);
  }

  rfor->in_do = calloc(1, sizeof (s_dogroup));

  if (g_data->lexer == NULL || rule_do_group(rfor->in_do) == NULL)
  {
    free(rfor->in_do);
    rfor->in_do = NULL;

    return (NULL);
  }

  return (rfor);
}
